package com.shangjinrong.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.shangjinrong.domain.dto.ExcelDictDto;
import com.shangjinrong.mapper.DictMapper;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Naruto
 */
@Slf4j
@NoArgsConstructor
public class ExcelDictDtoListener extends AnalysisEventListener<ExcelDictDto> {
    private DictMapper dictMapper;

    public ExcelDictDtoListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    private List<ExcelDictDto> list = new ArrayList<>();

    //每5条记录批量存储一次数据
    private static final int BATCH_COUNT = 5;

    @Override
    public void invoke(ExcelDictDto excelDictDto, AnalysisContext analysisContext) {
        //当最后的数据不足5条时，一次性存储剩余数据

        log.info("解析到一条数据：{}", excelDictDto);

        list.add(excelDictDto);

        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据全部解析完毕");
    }

    private void saveData() {
        log.info("{}条数据被存储到数据库", list.size());
        //调用mapper
        dictMapper.insertBatch(list);
    }
}
